package Grantsfire::Controller::Root;

use strict;
use warnings;
use base 'Catalyst::Controller';

#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config->{namespace} = '';

=head1 NAME

Grantsfire::Controller::Root - Root Controller for this Catalyst based application

=head1 SYNOPSIS

See L<Grantsfire>.

=head1 DESCRIPTION

Root Controller for this Catalyst based application.

=head1 METHODS

=cut

=head2 default

=cut

sub begin : Private {
    my ( $self, $c ) = @_;

    #$c->authorization_required( realm => "Grantsfire Site" ) unless defined $c->user;

    my @template = grep {$_ ne "" and !/\d/} $c->req->uri->path_segments;
    if (!@template) {
        @template = 'default';
    }
    if (-f $c->path_to('templates', @template) . '.tt') {
        $c->stash->{template} = join('/', @template) . '.tt';
    }
    elsif (! $c->res->body) {
        $c->log->info('No such template ' . $c->path_to('templates', @template) . '.tt');
    }
}

sub default : Private {
    my ( $self, $c ) = @_;

    my $rs = $c->model('GF::Feed')->search(
        undef,
        {order_by=>'created DESC', rows=>10})->page(1);
    $c->stash->{feeds} = [$rs->all];

    $rs = $c->model('GF::Entry')->search(
        undef,
        {order_by=>'modified DESC', rows=>10})->page(1);
    $c->stash->{grants} = [$rs->all];
    
    $rs = $c->model('GF::Search')->search(
        {query => {'!=', ''}},
        {order_by=>'hits DESC', rows=>10})->page(1);
    $c->stash->{top_searches} = [$rs->all];

    $c->stash->{total_grants} = $c->model('GF::Entry')->search(
        undef,
        {
            select => ['COUNT(id) AS total'],
            as => [qw/total/],
        }
    )->first->get_column('total') || 0;

    $c->stash->{total_funders} = $c->model('GF::Org')->search(
        undef,
        {
            select => ['COUNT(id) AS total'],
            as => [qw/total/],
        }
    )->first->get_column('total') || 0;

    $c->stash->{total_amount} = $c->model('GF::Entry')->search(
        undef,
        {
            select => ['SUM(amount) AS total'],
            as => [qw/total/],
        }
    )->first->get_column('total') || 0;

    if (!$c->stash->{template}) {
        $c->res->status(404);
        $c->stash->{template} = "404.tt";
    }
}

#
# Uncomment and modify this end action after adding a View component
#
#=head2 end
#
#=cut
#
#sub end : Private {
#    my ( $self, $c ) = @_;
#
#    # Forward to View unless response body is already defined
#    $c->forward( $c->view('') ) unless $c->response->body;
#}

=head1 AUTHOR

Keith Grennan

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
